package org.lmind.example.util.io;

import java.io.IOException;
import java.io.InputStream;

public class LimitInputStream extends InputStream {
	
	private int limit;
	
	private int totalReadSize;
	
	private InputStream host;

	public LimitInputStream(InputStream host, int limit) {
		this.host = host;
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public int getTotalReadSize() {
		return totalReadSize;
	}

	public InputStream getHost() {
		return host;
	}

	public int available() throws IOException {
		int t = host.available();
		return Math.min(t, limit - totalReadSize);
	}

	public void close() throws IOException {
		host.close();
	}

	@Override
	public int read() throws IOException {
		if (limit == totalReadSize) {
			return -1;
		}
		int r = host.read();
		if (r != -1) {
			totalReadSize++;
		}
		return r;
	}

}
